package pl.edu.utp.kursy.utils;

import java.awt.Desktop;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.log4j.Logger;
import pl.edu.utp.kursy.Application;

public class FileUtil {
    
    public static final Logger logger = Logger.getLogger(FileUtil.class);
    
    public static String getApplicationPath(){
        String path = Application.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(0, path.length());
        int i = path.lastIndexOf("/");
        path = path.substring(0, i); 
        try {
            path = URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            logger.error(ex.getMessage());
            return null;
        }
        return path;
    }
    
    public static File getInovicesDirectory(){
        File file = new File(getApplicationPath() + "/faktury");
	if (!file.exists()) {
		if (file.mkdir()) {
			logger.info("Directory is created!");
		} else {
			logger.error("Failed to create directory!");
		}
	}
        return file;
    }
    
    public static boolean openFile(String path){
        try {
		File pdfFile = new File(path);
		if (pdfFile.exists()) {
                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().open(pdfFile);
                        return true;
                    } else {
                        logger.warn("Awt Desktop is not supported!");
                    }
		}
	  } catch (Exception ex) {
		logger.error(ex.getMessage());
	  }
        return false;
    }
    
    public static boolean deleteFile(String path){
        File file = new File(path);
        return file.delete();
    }
}
